//
// Created by tonystark on 16/3/29.
// Copyright (c) 2016 sewm. All rights reserved.
//

#import <JSONKIT/JSONKit.h>
#import "Api.h"
#import "UpLoadData.h"


//#define  ServerUrl @"http://112.124.15.158:8080"
#define  ServerUrl @"http://120.76.99.97:8080"
#define  SubPathUrl @"/kuaidao/client/resources.html"
#define  kBody     @"body"
#define  kJson     @"json"
#define  kBusinessType     @"businessType"

#define  AppType     @"1"

@implementation Api {

}

+ (NSMutableDictionary *)baseJsonData {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"appType"] = AppType;
    dict[@"appVersion"] = APPVersionCode;
    return dict;
}

+ (void)handleSuccess:(AFHTTPRequestOperation *)operation responseObject:(id)responseObject successBlock:(SuccessBlock)success failBlock:(FailBlock)fail {
#ifdef DEBUG
    if (operation.request.HTTPBody) {
        DEBUG_LOG(@"\n%@?%@--\n[%@]", operation.request.URL, [[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding].stringByRemovingPercentEncoding, [responseObject JSONString_JSONKit]);
    } else {
        DEBUG_LOG(@"\n%@--\n[%@]", operation.request.URL, [responseObject JSONString_JSONKit]);
    }
#endif

    NSInteger status = [responseObject[@"status"] integerValue];
    if (1000 == status) {
        if (success) {
            id json = responseObject[kBody];
            success(json);
        }
    } else if (1001 == status) {
        //服务器返回空数据状态码时，处理成请求成功，回调一个空数组
        if (success) {
            success(@[]);
        }
    } else {
        if (fail) {
            fail(responseObject[@"message"], status);
        }
    }
}

+ (void)handleFailure:(AFHTTPRequestOperation *)operation error:(NSError *)error failBlock:(FailBlock)fail {
#ifdef DEBUG
    if (operation.request.HTTPBody) {
        DEBUG_LOG(@"%@?%@--\n%@", operation.request.URL, [[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding].stringByRemovingPercentEncoding, error);
    } else {
        DEBUG_LOG(@"%@--\n%@", operation.request.URL, error);
    }
#endif

    if (fail) {
        if (NSURLErrorNotConnectedToInternet == error.code) {
            fail(@"网络断开，请检查网络", error.code);
        } else {
            fail(@"连接服务器失败", error.code);
        }
    }
}

+ (AFHTTPRequestOperation *)getConnection:(SuccessBlock)success fail:(FailBlock)fail parameters:(NSDictionary *)paramDict method:(RequestMethod)method serviceName:(NSString *)serviceName {
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:[self baseJsonData]];
    data[kBusinessType] = SSJKString(serviceName);
    data[kBody] = [paramDict JSONString_JSONKit];
    return [self getConnection:success fail:fail urlPath:SubPathUrl parameters:data method:method];
}

/**
 * 创建请求
 * urlPath: 表示除了kApiServer外的url
 * paramDict: 表示全部的请求参数，比如包括了基本数据
 */
+ (AFHTTPRequestOperation *)getConnection:(SuccessBlock)success fail:(FailBlock)fail urlPath:(NSString *)urlPath parameters:(NSDictionary *)paramDict method:(RequestMethod)method {
#ifdef DEBUG
    DEBUG_LOG(@"[%@][%@]", urlPath, [paramDict JSONString_JSONKit]);
#endif

    AFHTTPRequestOperation *requestOperation;
    WeakSelf
    if (method == Method_Get) {
        requestOperation = [[ApiClient sharedInstance] GET:urlPath parameters:@{kJson : paramDict.JSONString_JSONKit} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [weakSelf handleSuccess:operation responseObject:responseObject successBlock:success failBlock:fail];
        }                                          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [weakSelf handleFailure:operation error:error failBlock:fail];
        }];
    } else {
        requestOperation = [[ApiClient sharedInstance] POST:urlPath parameters:@{kJson : paramDict.JSONString_JSONKit} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [weakSelf handleSuccess:operation responseObject:responseObject successBlock:success failBlock:fail];
        }                                           failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [weakSelf handleFailure:operation error:error failBlock:fail];
        }];
    }

    NSMutableURLRequest *request = (NSMutableURLRequest *) requestOperation.request;
    request.timeoutInterval = 30;
    return requestOperation;
}

+ (AFHTTPRequestOperation *)getConnection:(SuccessBlock)success fail:(FailBlock)fail urlPath:(NSString *)urlPath parameters:(NSDictionary *)paramDict datas:(NSArray *)datas {
    WeakSelf
    AFHTTPRequestOperation *requestOperation = [[ApiClient sharedInstance] POST:urlPath parameters:paramDict constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {

        for (id objc in datas) {
            if ([objc isKindOfClass:[UIImage class]]) {
                NSData *data = UIImageJPEGRepresentation((UIImage *) objc, 1);
                [formData appendPartWithFileData:data name:@"files" fileName:@"file.jpg" mimeType:@"image/jpeg"];
            } else if ([objc isKindOfClass:[UpLoadData class]]) {
                UpLoadData *data = objc;
                [formData appendPartWithFileData:data.data name:@"files" fileName:data.fileName mimeType:data.mimeType];
            }

        }
    }                                                                   success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [weakSelf handleSuccess:operation responseObject:responseObject successBlock:success failBlock:fail];
    }                                                                   failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf handleFailure:operation error:error failBlock:fail];
    }];

    NSMutableURLRequest *request = (NSMutableURLRequest *) requestOperation.request;
    request.timeoutInterval = 600;
    return requestOperation;
}

//带文件上传的请求
+ (AFHTTPRequestOperation *)getConnection:(SuccessBlock)success fail:(FailBlock)fail bodyDict:(NSDictionary *)bodyDict service:(NSString *)serviceName mutiDatas:(NSArray *)datas {
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[self paramesFormat:bodyDict service:serviceName]];
    return [self getConnection:success fail:fail urlPath:SubPathUrl parameters:dic datas:datas];
}

//请求参数组装
+ (NSDictionary *)paramesFormat:(NSDictionary *)bodyDict service:(NSString *)serviceName {
    NSMutableDictionary *jsonDict = [self baseJsonData];
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:bodyDict];
//    SystemSettingManager *manager = [SystemSettingManager sharedInstance];
//    if (manager.uid.length > 0) data[@"uid"] = manager.uid;
//    if (bodyDict) {
//        data[kGUID] = manager.guid;
//        data[kOS] = @"ios";
//        //      请求参数加密(3des)： 密码:md5(salt+E_KEY) | data加密:base64.encode(3des(json明文参数,密码))
//        //      Token验证：DigestUtils.md5(service + time + data + salt + version + E_KEY) E_KEY为:9HkocpYLeG1LNi5m ,注：data为上步骤中3des加密结果
//        NSString * salt = jsonDict[kSalt];//6位随机数
//        NSString * encrypt = [[NSString stringWithFormat:@"%@%@", salt, EKey] md5FromString];
//        NSString * mdData = [[NSString TripleDES:[data JSONString_JSONKit] encryptOrDecrypt:kCCEncrypt encryptOrDecryptKey:encrypt] base64EncodedString];
//        NSString * token = [[NSString stringWithFormat:@"%@%@%@%@%@%@", serviceName, jsonDict[kTime], mdData, salt, jsonDict[kVersion], EKey] md5FromString];
//        jsonDict[kToken] = token;
//    }
//    jsonDict[kData] = [data JSONString_JSONKit];
//    jsonDict[kService] = serviceName;
//    jsonDict[kTest] = @"yes";

    return jsonDict;
}

+ (AFHTTPRequestOperation *)uploadImgFile:(NSArray *)images successBlock:(SuccessBlock)success failBlock:(FailBlock)fail {
    return [self getConnection:success fail:fail bodyDict:@{@"dir" : @"photo"} service:@"upload" mutiDatas:images];
}

@end

@implementation ApiClient

+ (instancetype)sharedInstance {
    static ApiClient *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[ApiClient alloc] initWithBaseURL:[NSURL URLWithString:ServerUrl]];
    });
    return instance;
}
@end